from bodhi.utils.security import sign, unsign

class AuthProviderBase:
    def __init__(self, get_user, secret=None, cookie_name='user', age=86400*7):
        self.get_user = get_user
        self.secret = secret
        self.cookie_name = cookie_name
        self.age = age

    def authenticate(self, view):
        cookie = view.request.get_cookie(self.cookie_name)
        if cookie:
            try:
                if self.secret:
                    cookie = unsign(self.secret, cookie, self.age)
                return self.get_user(int(cookie))
            except Exception:
                pass

    def login(self, view, user):
        view._user = user
        cookie = str(view.user.id)
        if self.secret:
            cookie = sign(self.secret, cookie)
        view.response.set_cookie(self.cookie_name,
                cookie,
                max_age=self.age)

    def logout(self, view):
        view.response.delete_cookie(self.cookie_name)

